package com.剑指offer.第四章;

/**
 * 给定一个链表，链表中节点的顺序是L0--L1--L2.....--Ln-1--Ln
 * 请问如何重排链表使节点的顺序变成L0--Ln--L1--Ln-1--L2.....
 */
public class 重排链表 {

    public static ListNode convert(ListNode head) {
        ListNode pre = null;
        ListNode node = head;
        while (node != null) {
            ListNode next = node.next;
            node.next = pre;
            pre = node;
            node = next;
        }
        return pre;
    }

    public static void resolve(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;

        ListNode slow = dummy;
        ListNode fast = dummy;

        // 使用快慢指针找出中间的节点
        while (fast.next != null) {
            slow = slow.next;
            fast = fast.next;
            if (fast.next != null) {
                fast = fast.next;
            }
        }
        ListNode node2 = slow.next;
        // 与下一半的节点 断开
        slow.next = null;

        // 反转后半段节点
        repeatNode(head, convert(node2), dummy);
    }

    public static void repeatNode(ListNode node1, ListNode node2, ListNode head) {
        ListNode pre = head;
        while (node1 != null && node2 != null) {
            ListNode temp = node1.next;
            pre.next = node1;
            node1.next = node2;
            pre = node2;
            node1 = temp;
            node2 = node2.next;
        }
        if (node1 != null) {
            pre.next = node1;
        }

    }

    public static void main(String[] args) {
        ListNode head = new ListNode(0);
        ListNode p1 = new ListNode(1);
        ListNode p2 = new ListNode(2);
        ListNode p3 = new ListNode(3);
        ListNode p4 = new ListNode(4);
        ListNode p5 = new ListNode(5);
        head.next = p1;
        p1.next = p2;
        p2.next = p3;
        p3.next = p4;
        p4.next = p5;
        resolve(head);
        ListNode fist = head;
        while (fist != null) {
            System.out.println(fist.val);
            fist = fist.next;
        }

    }

}
